package com.cn.ycy.config;

import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class LogConfigListener {

  @Resource
  private LoggingSystem loggingSystem;

  private final Logger logger = LoggerFactory.getLogger(getClass());

  /**
   * 没有成功
   *
   * @param changeEvent
   */
  @ApolloConfigChangeListener("application")
  private void onChange(ConfigChangeEvent changeEvent) {
    for (String key : changeEvent.changedKeys()) {
      if (key.equals("logging.level.root")) {
        String strLevel = changeEvent.getChange(key).getNewValue();

        LogLevel level;
        try {
          level = LogLevel.valueOf(strLevel.toUpperCase());
        } catch (IllegalArgumentException e) {
          logger.error("the config of log level({}) is error,so provided the info level!", strLevel);
          level = LogLevel.INFO;
        }

        logger.info("change logger level {}:{}", key, level.name());
        loggingSystem.setLogLevel("", level);
      }
    }
  }

}
